package com.nutrition.health.controller;

import com.nutrition.health.model.FoodItem;
import com.nutrition.health.model.NutritionInfo;
import com.nutrition.health.repository.NutritionInfoRepository;
import com.nutrition.health.service.FoodItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 食品信息控制器
 * 处理食品分析相关的API请求
 */
@RestController
@RequestMapping("/food-items")
@Api(tags = "食品信息管理", description = "食品信息的CRUD操作和食品分析功能")
public class FoodItemController {

    private final FoodItemService foodItemService;
    private final NutritionInfoRepository nutritionInfoRepository;

    @Autowired
    public FoodItemController(FoodItemService foodItemService, NutritionInfoRepository nutritionInfoRepository) {
        this.foodItemService = foodItemService;
        this.nutritionInfoRepository = nutritionInfoRepository;
    }

    /**
     * 获取所有食品信息
     * @return 食品信息列表
     */
    @GetMapping
    @ApiOperation(value = "获取所有食品信息", notes = "返回系统中所有已记录的食品信息")
    public ResponseEntity<List<FoodItem>> getAllFoodItems() {
        List<FoodItem> foodItems = foodItemService.getAllFoodItems();
        return ResponseEntity.ok(foodItems);
    }

    /**
     * 根据ID获取食品信息
     * @param id 食品ID
     * @return 食品信息
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID获取食品信息", notes = "根据提供的ID返回对应的食品详细信息")
    public ResponseEntity<FoodItem> getFoodItemById(
            @ApiParam(value = "食品ID", required = true) @PathVariable Long id) {
        return foodItemService.getFoodItemById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 创建新的食品信息
     * @param foodItem 食品信息对象
     * @return 创建的食品信息
     */
    @PostMapping
    @ApiOperation(value = "创建新的食品信息", notes = "添加新的食品到系统")
    public ResponseEntity<FoodItem> createFoodItem(
            @ApiParam(value = "食品信息对象", required = true) @RequestBody FoodItem foodItem) {
        FoodItem createdFoodItem = foodItemService.createFoodItem(foodItem);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdFoodItem);
    }

    /**
     * 更新食品信息
     * @param id 食品ID
     * @param foodItem 更新的食品信息
     * @return 更新后的食品信息
     */
    @PutMapping("/{id}")
    @ApiOperation(value = "更新食品信息", notes = "根据ID更新已有的食品信息")
    public ResponseEntity<FoodItem> updateFoodItem(
            @ApiParam(value = "食品ID", required = true) @PathVariable Long id,
            @ApiParam(value = "更新的食品信息", required = true) @RequestBody FoodItem foodItem) {
        return foodItemService.getFoodItemById(id)
                .map(existingFoodItem -> {
                    foodItem.setId(id);
                    FoodItem updatedFoodItem = foodItemService.updateFoodItem(id, foodItem);
                    return ResponseEntity.ok(updatedFoodItem);
                })
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 删除食品信息
     * @param id 食品ID
     * @return 无内容响应
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除食品信息", notes = "根据ID删除食品信息")
    public ResponseEntity<Void> deleteFoodItem(
            @ApiParam(value = "食品ID", required = true) @PathVariable Long id) {
        return foodItemService.getFoodItemById(id)
                .map(foodItem -> {
                    foodItemService.deleteFoodItem(id);
                    return ResponseEntity.noContent().<Void>build();
                })
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 通过图片分析食品
     * @param image 食品图片
     * @return 分析结果
     */
    @PostMapping("/analyze-image")
    @ApiOperation(value = "通过图片分析食品", notes = "上传食品图片，AI分析识别食品并返回营养成分")
    public ResponseEntity<Map<String, Object>> analyzeFoodByImage(
            @ApiParam(value = "食品图片", required = true) @RequestParam("image") MultipartFile image) {
        try {
            // 调用服务进行图像分析
            FoodItem analyzedFood = foodItemService.analyzeFoodImage(image);
            
            // 构建响应结果
            Map<String, Object> result = new HashMap<>();
            
            // 添加食品信息
            result.put("name", analyzedFood.getName());
            result.put("category", analyzedFood.getCategory().toString());
            result.put("description", analyzedFood.getDescription());
            
            // 添加营养信息
            NutritionInfo nutritionInfo = nutritionInfoRepository.findByFoodItemId(analyzedFood.getId()).orElse(null);
            if (nutritionInfo != null) {
                result.put("calories", nutritionInfo.getCalories());
                result.put("protein", nutritionInfo.getProtein());
                result.put("fat", nutritionInfo.getFat());
                result.put("carbs", nutritionInfo.getCarbohydrates());
                result.put("fiber", nutritionInfo.getFiber());
                
                // 添加维生素信息
                Map<String, String> vitamins = new HashMap<>();
                if (nutritionInfo.getVitaminA() != null && nutritionInfo.getVitaminA() > 0) {
                    vitamins.put("A", nutritionInfo.getVitaminA() + "%");
                }
                if (nutritionInfo.getVitaminC() != null && nutritionInfo.getVitaminC() > 0) {
                    vitamins.put("C", nutritionInfo.getVitaminC() + "%");
                }
                result.put("vitamins", vitamins);
                
                // 添加矿物质信息
                Map<String, String> minerals = new HashMap<>();
                if (nutritionInfo.getCalcium() != null && nutritionInfo.getCalcium() > 0) {
                    minerals.put("钙", nutritionInfo.getCalcium() + "mg");
                }
                if (nutritionInfo.getIron() != null && nutritionInfo.getIron() > 0) {
                    minerals.put("铁", nutritionInfo.getIron() + "mg");
                }
                if (nutritionInfo.getPotassium() != null && nutritionInfo.getPotassium() > 0) {
                    minerals.put("钾", nutritionInfo.getPotassium() + "mg");
                }
                if (nutritionInfo.getSodium() != null && nutritionInfo.getSodium() > 0) {
                    minerals.put("钠", nutritionInfo.getSodium() + "mg");
                }
                result.put("minerals", minerals);
                
                // 添加其他信息
                result.put("additionalInfo", nutritionInfo.getAdditionalNutrients());
            }
            
            // 添加图片URL（如果有）
            if (analyzedFood.getImageUrl() != null && !analyzedFood.getImageUrl().isEmpty()) {
                result.put("imageUrl", analyzedFood.getImageUrl());
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "分析食品图片失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(errorResponse);
        }
    }

    /**
     * 通过条形码查询食品
     * @param barcode 条形码
     * @return 食品信息
     */
    @GetMapping("/barcode/{barcode}")
    @ApiOperation(value = "通过条形码查询食品", notes = "根据条形码返回对应的食品信息")
    public ResponseEntity<FoodItem> getFoodItemByBarcode(
            @ApiParam(value = "条形码", required = true) @PathVariable String barcode) {
        return foodItemService.getFoodItemByBarcode(barcode)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 搜索食品
     * @param query 搜索关键词
     * @return 匹配的食品列表
     */
    @GetMapping("/search")
    @ApiOperation(value = "搜索食品", notes = "根据关键词搜索食品")
    public ResponseEntity<Page<FoodItem>> searchFoodItems(
            @ApiParam(value = "搜索关键词", required = true) @RequestParam String query,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<FoodItem> foodItems = foodItemService.searchFoodItems(query, pageable);
        return ResponseEntity.ok(foodItems);
    }
}